package com.wx.service.client.config.service.impl;

import com.wx.service.accesstoken.service.IAccessTokenService;
import com.wx.service.client.config.service.IWConfigService;
import com.wx.service.client.config.vo.WxConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.UUID;

@Service
public class WxConfigServiceImpl implements IWConfigService {

  private static final Logger LOGGER = LoggerFactory.getLogger(WxConfigServiceImpl.class);
  @Value("${wx.corpid}")
  private String corpid;

  @Value("${wx.corpsecret}")
  private String corpsecret;

  @Value("${wx.aesKey}")
  private String aesKey;

  @Value("${wx.jsapiticket.url}")
  private String jsApiTicketUrl;

  @Autowired
  private IAccessTokenService accessTokenService;

  @Autowired
  private RestTemplate restTemplate;

  @Override
  public WxConfig getWXConfig(String url) {
    WxConfig wxConfig = new WxConfig();
    String accessToken = accessTokenService.getAccessToken();
    wxConfig.setAccessToken(accessToken);
    String jsApiTicket = getJsApiTicket(accessToken);
    wxConfig.setJsApiTicket(jsApiTicket);
    String noncestr = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    Long timestamp = System.currentTimeMillis();
    String str1 = "jsapi_ticket=" + jsApiTicket +
        "&noncestr=" + noncestr +
        "&timestamp=" + timestamp +
        "&url=" + url;
    String signature = DigestUtils.sha1Hex(str1.getBytes());
    wxConfig.setAppId(corpid);
    wxConfig.setTimestamp(timestamp);
    wxConfig.setNonceStr(noncestr);
    wxConfig.setSignature(signature);
    return wxConfig;
  }

  private String getJsApiTicket(String accessToken) {
    Map map = restTemplate.getForObject(jsApiTicketUrl.replace("{accessToken}", accessToken), Map.class);
    return map.get("ticket").toString();
  }
}
